package com.bc.trade.channel.suning.util;

import java.io.UnsupportedEncodingException;
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Digest {
	private static Logger LOGGER = LoggerFactory.getLogger(Digest.class);

	public static String digest(String str) {
		String md5 = null;
		try {
			LOGGER.debug("生成的字符串为:{}", (Object) str);
			md5 = MD5.digest((String) str, (String) "UTF-8");
			LOGGER.debug("生成的Md5摘要为:{}", (Object) md5);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
		return md5;
	}

	public static String digest(Map<String, String> map, String... keys) {
		TreeMap<String, String> treeMap = Digest.treeMap(map, keys);
		return Digest.digest(Digest.mapToString(treeMap));
	}

	public static TreeMap<String, String> treeMap(Map<String, String> map, String... keys) {
		StringComparator stringComparator = new StringComparator();
		TreeMap<String, String> treeMap = new TreeMap<String, String>((Comparator<String>) stringComparator);
		treeMap.putAll(map);
		for (String key : keys) {
			treeMap.remove(key);
		}
		return treeMap;
	}

	public static String mapToString(Map<String, String> map) {
		StringBuilder result = new StringBuilder();
		for (Map.Entry<String, String> entry : map.entrySet()) {
			String value = entry.getValue() == null ? "" : entry.getValue().trim();
			result.append(entry.getKey()).append("=").append(value).append("&");
		}
		if (result.length() > 0) {
			result.deleteCharAt(result.length() - 1);
		}
		return result.toString().trim();
	}
}
